﻿using System;
using System.Windows.Forms;
using QuanLyThuPhiTaiLieu.Biz;
using QuanLyThuPhiTaiLieu.Common;
using QuanLyThuPhiTaiLieu.Entity;
using System.IO;
using Telerik.WinControls.UI;
using System.Collections.Generic;
using System.Globalization;

namespace QuanLyThuPhiTaiLieu.Forms
{
    public partial class NewBangKeKhaiPhiSuDungChiTiet : Form
    {
        private int id;
        private int parentId;
        private int danhMucId;
        private int khaiThacId = 0;
        private int thamKhaoId = 0;
        private int isSave;        

        public NewBangKeKhaiPhiSuDungChiTiet()
        {
            InitializeComponent();

            labelMucThu.Visible = false;
            drlMucThu.Visible = false;
            drlMucThu.TabStop = false;

            isSave = 0;
        } 

        public NewBangKeKhaiPhiSuDungChiTiet(int id)
        {
            InitializeComponent();

            labelMucThu.Visible = false;
            drlMucThu.Visible = false;
            drlMucThu.TabStop = false;

            this.id = id;

            isSave = 0;
        }

        private void SaveItem(object sender, EventArgs e)
        {
            if (Validate())
            {
                string message;

                var biz = new PhieuBanGiaoTaiLieuChiTietBiz();

                string mucThu = string.Empty;
                if (drlMucThu.Visible)
                {
                    mucThu = GetMucThu(drlMucThu.SelectedItem.Text);
                }
                
                var item = new PhieuBanGiaoTaiLieuChiTiet
                {
                    DonGia = Convert.ToDecimal(numberDonGia.Value),
                    MaTaiLieu = textMaTaiLieu.Text,
                    NoiDungYeuCau = textNoiDungYeuCau.Text,
                    SoLuong = Convert.ToInt32(numberSoLuong.Value),
                    ThanhTien = Convert.ToDecimal(numberThanhTien.Value),
                    TenTaiLieu = drlTenTaiLieu.Text,
                    DonViTinh = textDonViTinh.Text,
                    LoaiTaiLieu = textLoaiTaiLieu.Text,
                    DangTaiLieu = textDangTaiLieu.Text,
                    Khlt = textKhlt.Text,
                    TenBaoCao = textTenBaoCao.Text,
                    MaBaoCao = drlLoaiTaiLieu.SelectedItem.Value.ToString(),
                    MucThu = mucThu
                };

                if (id > 0)
                {
                    item.Id = id;
                    item.PhieuBanGiao = parentId;
                    biz.UpdateItem(item);

                    message = Constants.Messages.UpdateCompleted;
                }
                else
                {
                    biz.SaveItem(item);
                    message = Constants.Messages.InsertCompleted;
                }

                //MessageBox.Show(message);

                var parent = this.Owner.ActiveMdiChild as NewBangKeKhaiPhiSuDung;
                if (parent != null)
                {
                    var list = parent.ListChiTiet;
                    if (id > 0)
                    {
                        for (int i = 0; i < list.Count; i++)
                        {
                            if (list[i].Id == id)
                            {
                                list.RemoveAt(i);
                                list.Insert(i, item);
                            }
                        }
                    }
                    else
                    {
                        list.Add(item);
                    }

                    parent.ListChiTiet = list;
                    parent.RefreshDetailView(0);
                }
                
                if(id > 0)
                {
                    this.Close();                    
                }
                else
                {
                    ResetControls();
                    isSave = 0;
                }
            }
        }

        private void Cancel(object sender, EventArgs e)
        {
            this.Close();
        }

        private new bool Validate()
        {
            bool hasError = true;
            bool isFocused = false;
            errorProvider.Clear();

            if (string.IsNullOrEmpty(textKhlt.Text))
            {
                hasError = false;
                isFocused = true;
                errorProvider.SetError(textKhlt, Constants.Messages.RequireMessage);
                textKhlt.Focus();
            }

            if (string.IsNullOrEmpty(drlTenTaiLieu.Text))
            {
                hasError = false;
                errorProvider.SetError(drlTenTaiLieu, Constants.Messages.RequireMessage);
                if (!isFocused)
                {
                    drlTenTaiLieu.Focus();
                    isFocused = true;
                }
            }

            if (string.IsNullOrEmpty(drlLoaiTaiLieu.SelectedItem.Value.ToString()))
            {
                hasError = false;
                errorProvider.SetError(drlLoaiTaiLieu, Constants.Messages.RequireMessage);
                if (!isFocused)
                {
                    drlLoaiTaiLieu.Focus();
                    isFocused = true;
                }
            }

            if (drlMucThu.Visible && string.IsNullOrWhiteSpace(drlMucThu.Text))
            {
                hasError = false;
                errorProvider.SetError(drlMucThu, Constants.Messages.RequireMessage);
                if (!isFocused)
                {
                    drlMucThu.Focus();
                    isFocused = true;
                }
            }

            var thanhTien = Convert.ToDecimal(numberThanhTien.Value);
            if (thanhTien == 0)
            {
                hasError = false;
                errorProvider.SetError(numberThanhTien, Constants.Messages.RequireMessage);
            }

            return hasError;
        }
        
        private void LoadLoaiTaiLieu()
        {
            drlLoaiTaiLieu.Items.Clear();

            var item = new RadListDataItem();
            item.Text = "Báo cáo điều tra, tìm kiếm, đánh giá, thăm dò khoáng sản";
            item.Value = "II.A";
            drlLoaiTaiLieu.Items.Add(item);

            item = new RadListDataItem();
            item.Text = "Báo cáo đo vẽ lập bản đồ địa chất khoáng sản";
            item.Value = "II.B";
            drlLoaiTaiLieu.Items.Add(item);

            item = new RadListDataItem();
            item.Text = "Báo cáo địa chất đô thị";
            item.Value = "II.C";
            drlLoaiTaiLieu.Items.Add(item);

            item = new RadListDataItem();
            item.Text = "Báo cáo Địa chất thủy văn - Địa chất công trình";
            item.Value = "II.D";
            drlLoaiTaiLieu.Items.Add(item);

            item = new RadListDataItem();
            item.Text = "Báo cáo Địa vật lý";
            item.Value = "II.E";
            drlLoaiTaiLieu.Items.Add(item);

            item = new RadListDataItem();
            item.Text = "Tài liệu quy hoạch điều tra cơ bản địa chất về tài nguyên khoáng sản; quy hoạch thăm dò, khai thác, chế biến và sử dụng khoáng sản";
            item.Value = "II.G";
            drlLoaiTaiLieu.Items.Add(item);

            item = new RadListDataItem();
            item.Text = "Báo cáo nghiên cứu chuyên đề";
            item.Value = "II.H";
            drlLoaiTaiLieu.Items.Add(item);

            item = new RadListDataItem();
            item.Text = "Tham khảo tài liệu";
            item.Value = "TKTL";
            drlLoaiTaiLieu.Items.Add(item);

            item = new RadListDataItem();
            item.Text = string.Empty;
            item.Value = string.Empty;
            drlLoaiTaiLieu.Items.Insert(0, item);
        }        

        private void FormLoad(object sender, EventArgs e)
        {
            var parent = MdiParent as MDI;
            if (parent != null)
            {
                //Utilities.ResetBackColor(parent.TopMenu, Constants.MenuIndex.TaiLieuVanBanPhapLy);
                parent.Status.Text = Constants.FormStatus.PhieuBanGiao;                
            }

            LoadLoaiTaiLieu();

            if (id > 0)
            {
                var biz = new PhieuBanGiaoTaiLieuChiTietBiz();
                var item = biz.LoadItem(id);

                textKhlt.Text = item.Khlt;
                textTenBaoCao.Text = item.TenBaoCao;
                drlLoaiTaiLieu.SelectedValue = item.MaBaoCao;
                                
                textMaTaiLieu.Text = item.MaTaiLieu;
                textNoiDungYeuCau.Text = item.NoiDungYeuCau;
                textDonViTinh.Text = item.DonViTinh;
                numberDonGia.Value = item.DonGia;
                numberSoLuong.Value = item.SoLuong;
                numberThanhTien.Value = item.ThanhTien;
                parentId = item.PhieuBanGiao;

                if (!string.IsNullOrWhiteSpace(item.MucThu))
                {
                    var khaiThacBiz = new KhaiThacVaSuDungTaiLieuBiz();
                    var khaiThacItem = khaiThacBiz.LoadItem(item.MaTaiLieu);

                    labelMucThu.Visible = true;
                    drlMucThu.Visible = true;
                    drlMucThu.TabStop = true;
                    drlMucThu.Items.Clear();

                    AddMucThu("Photo", khaiThacItem.MucThuPhoto, drlMucThu);
                    AddMucThu("In", khaiThacItem.MucThuIn, drlMucThu);
                    AddMucThu("Word, Excel", khaiThacItem.MucThuOffice, drlMucThu);
                    AddMucThu("Rastor", khaiThacItem.MucThuRastor, drlMucThu);
                    AddMucThu("Vector", khaiThacItem.MucThuVector, drlMucThu);

                    string mucLuc = item.MucThu.Trim();

                    foreach (var i in drlMucThu.Items)
                    {
                        if ((string.Equals(i.Text, "Photo", StringComparison.InvariantCultureIgnoreCase) && string.Equals(mucLuc, ".a", StringComparison.InvariantCultureIgnoreCase)) ||
                        (string.Equals(i.Text, "In", StringComparison.InvariantCultureIgnoreCase) && string.Equals(mucLuc, ".b", StringComparison.InvariantCultureIgnoreCase)) ||
                        (string.Equals(i.Text, "Word, Excel", StringComparison.InvariantCultureIgnoreCase) && string.Equals(mucLuc, ".c", StringComparison.InvariantCultureIgnoreCase)) ||
                        (string.Equals(i.Text, "Rastor", StringComparison.InvariantCultureIgnoreCase) && string.Equals(mucLuc, ".d", StringComparison.InvariantCultureIgnoreCase)) ||
                        (string.Equals(i.Text, "Vector", StringComparison.InvariantCultureIgnoreCase) && string.Equals(mucLuc, ".e", StringComparison.InvariantCultureIgnoreCase)))
                        {
                            i.Selected = true;
                        }
                    }

                    for (int i = 0; i < drlTenTaiLieu.Items.Count; i++)
                    {
                        var listItem = (RadListDataItem)drlTenTaiLieu.Items[i];
                        if (string.Equals(listItem.Text, khaiThacItem.TenLoaiTaiLieu, StringComparison.InvariantCultureIgnoreCase))
                        {
                            drlTenTaiLieu.SelectedIndex = i;
                            break;
                        }
                    }

                }
                else
                {
                    var pBiz = new ThamKhaoTaiLieuBiz();
                    var thamKhao = pBiz.LoadItem(item.MaTaiLieu);

                    for (int i = 0; i < drlTenTaiLieu.Items.Count; i++)
                    {
                        var listItem = (RadListDataItem)drlTenTaiLieu.Items[i];
                        if (string.Equals(listItem.Text, thamKhao.LoaiTaiLieu, StringComparison.InvariantCultureIgnoreCase))
                        {
                            drlTenTaiLieu.SelectedIndex = i;
                            break;
                        }
                    }
                }

                textNoiDungYeuCau.Text = item.NoiDungYeuCau;
                numberSoLuong.Value = item.SoLuong;
                numberThanhTien.Value = item.ThanhTien;
                numberDonGia.Value = item.DonGia;
            }
        }

        public void UpdateKhlt(string khlt, string tenBaoCao, int id)
        {
            textTenBaoCao.Text = tenBaoCao;
            danhMucId = id;
            textKhlt.Text = khlt;
        }

        private void KhltKeyEvent(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                var biz = new DanhMucBiz();
                var item = biz.LoadItem(textKhlt.Text);
                if (item != null)
                {
                    textTenBaoCao.Text = item.TenBaoCao;
                    danhMucId = item.Id;
                }
                else
                {
                    MessageBox.Show("Không tìm được danh mục nào");
                }
            }
        }

        private void SelectLoaiTaiLieu(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            drlTenTaiLieu.Items.Clear();
            drlTenTaiLieu.SelectedText = string.Empty;

            ResetControls();           
            
            var selectItem = drlLoaiTaiLieu.SelectedItem;
            if (selectItem != null)
            {
                string value = Convert.ToString(selectItem.Value);
                if (!string.IsNullOrEmpty(value))
                {
                    if(string.Equals(value, "TKTL", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var bizThamKhao = new ThamKhaoTaiLieuBiz();
                        var itemThamKhaos = bizThamKhao.ViewAll();
                        foreach (var thamKhao in itemThamKhaos)
                        {
                            var item = new RadListDataItem(thamKhao.LoaiTaiLieu, thamKhao);
                            drlTenTaiLieu.Items.Add(item);
                        }

                        textNoiDungYeuCau.Enabled = false;
                        textNoiDungYeuCau.TabStop = false;
                    }
                    else
                    {
                        var bizKhaiThac = new KhaiThacVaSuDungTaiLieuBiz();
                        var items = bizKhaiThac.LoadItemByMa(value);

                        if (items != null)
                        {
                            foreach (var khaiThac in items)
                            {
                                var item = new RadListDataItem(khaiThac.TenLoaiTaiLieu, khaiThac);
                                drlTenTaiLieu.Items.Add(item);
                            }
                        }

                        textNoiDungYeuCau.Enabled = true;
                        textNoiDungYeuCau.TabStop = true;
                    }
                }
            }        
        }

        private void NoiDungKeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != (char)Keys.Enter) return;

            var numbers = new List<int>();

            int soLuong = Utilities.GetPageNumber(textNoiDungYeuCau.Text, numbers);
            if (soLuong > 0)
            {
                if (ValidateSoLuong(numbers, soLuong))
                {
                    errorProvider.Clear();

                    numberSoLuong.Value = soLuong;

                    var donGia = Convert.ToDecimal(numberDonGia.Value);
                    if (donGia > 0)
                    {
                        numberThanhTien.Value = donGia * soLuong;

                        if (isSave == 1)
                        {
                            this.SaveItem(sender, e);
                        }
                        else
                        {
                            isSave++;
                        }                        
                    }
                }
                else
                {
                    errorProvider.SetError(textNoiDungYeuCau, Constants.Messages.InvalidaNumberMessage);
                }
            }            
        }        

        private void SelectMucThu(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            if (drlMucThu.Items.Count > 0 && drlMucThu.SelectedItem != null)
            {
                string value = Convert.ToString(drlMucThu.SelectedItem.Value);
                if (string.IsNullOrEmpty(value))
                {
                    numberDonGia.Value = 0;
                }
                else
                {
                    var donGia = Convert.ToDecimal(value);                    
                    var soLuong = Convert.ToDecimal(numberSoLuong.Value);

                    numberDonGia.Value = donGia;

                    if(soLuong > 0 && donGia > 0)
                    {
                        numberThanhTien.Value = soLuong * donGia;
                    }
                }
            }
        }

        private bool ValidateSoLuong(List<int> numbers, int soLuong)
        {
            return true;

            /*
            var biz = new DanhMucBoSungBiz();
            var items = biz.GetAllBanVe(danhMucId, thamKhaoId, khaiThacId);
            if (items != null && items.Count > 0)
            {
                var boSung = items[0];

                var sourceNumber = new List<int>();
                var max = Utilities.GetPageNumber(boSung.NoiDung, sourceNumber);
                numbers.Sort();

                if (soLuong <= max)
                {
                    if (numbers[0] >= sourceNumber[0] && numbers[numbers.Count - 1] <= sourceNumber[sourceNumber.Count - 1])
                        return true;
                }
            }
            return false;
             * */
        }

        private void SoLuongKeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != (char)Keys.Enter) return;

            var soLuong = Convert.ToDecimal(numberSoLuong.Value);

            var donGia = Convert.ToDecimal(numberDonGia.Value);
            if (soLuong > 0 && donGia > 0)
            {
                numberThanhTien.Value = soLuong * donGia;

                if (isSave == 1)
                {
                    this.SaveItem(sender, e);
                }
                else
                {
                    isSave++;
                }                        
            }            
        }
        
        private void AddMucThu(string name, decimal? gia, RadDropDownList control)
        {
            if (gia.HasValue)
            {
                var item = new RadListDataItem();
                item.Text = name;
                item.Value = gia;
                control.Items.Add(item);
            }
        }

        private string GetMucThu(string value)
        {
            string mucthu = string.Empty;
            switch (value)
            {
                case "Photo":
                    mucthu = ".a";
                    break;
                case "In":
                    mucthu = ".b";
                    break;
                case "Word, Excel":
                    mucthu = ".c";
                    break;
                case "Rastor":
                    mucthu = ".d";
                    break;
                case "Vector":
                    mucthu = ".e";
                    break;
                default:
                    break;
            }

            return mucthu;
        }

        public void ResetControls()
        {            
            textMaTaiLieu.Text = string.Empty;
            textNoiDungYeuCau.Text = string.Empty;
            textDonViTinh.Text = string.Empty;
            textDangTaiLieu.Text = string.Empty;
            textLoaiTaiLieu.Text = string.Empty;
            numberDonGia.Value = 0;
            numberSoLuong.Value = 0;
            numberThanhTien.Value = 0;
            drlMucThu.Items.Clear();

            labelMucThu.Visible = false;
            drlMucThu.Visible = false;
            drlMucThu.TabStop = false;
        }

        private void SelectTenTaiLieu(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            textNoiDungYeuCau.Text = string.Empty;
            numberDonGia.Value = 0;
            numberSoLuong.Value = 0;
            numberThanhTien.Value = 0;

            if (drlTenTaiLieu.SelectedItem == null) return;
            
            object selectedItem = ((RadListDataItem)drlTenTaiLieu.SelectedItem).Value;

            if (selectedItem is ThamKhaoTaiLieu)
            {
                var thamKhao = selectedItem as ThamKhaoTaiLieu;                
                textMaTaiLieu.Text = thamKhao.MaTaiLieu;
                textDonViTinh.Text = thamKhao.DonViTinh;
                numberDonGia.Value = thamKhao.Phi;
                thamKhaoId = thamKhao.Id;
            }
            else
            {
                if (selectedItem is KhaiThacVaSuDungTaiLieu)
                {
                    var khaiThac = selectedItem as KhaiThacVaSuDungTaiLieu;

                    textMaTaiLieu.Text = khaiThac.MaTaiLieu;
                    textDangTaiLieu.Text = khaiThac.DangLoaiTaiLieu;
                    textLoaiTaiLieu.Text = khaiThac.LoaiTaiLieu;
                    textDonViTinh.Text = khaiThac.DonViTinh;

                    labelMucThu.Visible = true;
                    drlMucThu.Visible = true;
                    drlMucThu.TabStop = true;
                    drlMucThu.Items.Clear();

                    AddMucThu("Photo", khaiThac.MucThuPhoto, drlMucThu);
                    AddMucThu("In", khaiThac.MucThuIn, drlMucThu);
                    AddMucThu("Word, Excel", khaiThac.MucThuOffice, drlMucThu);
                    AddMucThu("Rastor", khaiThac.MucThuRastor, drlMucThu);
                    AddMucThu("Vector", khaiThac.MucThuVector, drlMucThu);
                    khaiThacId = khaiThac.Id;
                }
            }

            /* Disable select ban ve 
            if (string.Equals(textDonViTinh.Text, "Bản vẽ", StringComparison.InvariantCultureIgnoreCase))
            {
                buttonSelectBanVe.Visible = true;
                textNoiDungYeuCau.Size = new System.Drawing.Size(377, 21);
            }
            else
            {
                textNoiDungYeuCau.Size = new System.Drawing.Size(458, 21);
                buttonSelectBanVe.Visible = false;
            }
            */
        }

        private void SelectBanVe(object sender, EventArgs e)
        {
            string data = textNoiDungYeuCau.Text;

            var formSelect = new SelectBanVe(danhMucId, khaiThacId, thamKhaoId, data);
            formSelect.ShowDialog();
            textNoiDungYeuCau.Text = formSelect.Result;

            if (string.IsNullOrEmpty(textNoiDungYeuCau.Text))
            {
                numberSoLuong.Value = 0;
                numberThanhTien.Value = 0;
            }

            var numbers = new List<int>();

            int soLuong = Utilities.GetPageNumber(textNoiDungYeuCau.Text, numbers);
            if (soLuong > 0)
            {
                numberSoLuong.Value = soLuong;

                var donGia = Convert.ToDecimal(numberDonGia.Value);
                if (donGia > 0)
                {
                    numberThanhTien.Value = donGia * soLuong;
                }
            }   
        }

        private void OpenNewDanhMuc(object sender, EventArgs e)
        {
            var form = new NewDanhMuc();
            form.StartPosition = FormStartPosition.CenterScreen;
            form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            form.IsDialog = true;

            var result = form.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                UpdateKhlt(form.DanhMucKhlt, form.DanhMucTenBaoCao, form.DanhMucId);
            }
        }        
    }
}
